<template>
  <LoginCheck>
    <div class="orders">
      <!-- 订单状态筛选 -->
      <van-tabs v-model="activeTab" sticky @change="handleTabChange">
        <van-tab title="全部" name="all" />
        <van-tab title="待支付" name="pending" />
        <van-tab title="待使用" name="using" />
        <van-tab title="已完成" name="completed" />
        <van-tab title="已退款" name="refunded" />
      </van-tabs>

      <!-- 订单列表 -->
      <div class="order-list">
        <div v-for="order in filteredOrders" :key="order.id" class="order-item" @click="viewOrderDetail(order)">
          <div class="order-header">
            <div class="store-info">
              <img :src="order.store_logo" :alt="order.store_name" />
              <span class="store-name">{{ order.store_name }}</span>
            </div>
          </div>

          <div class="order-content">
            <div class="product-info">
              <img :src="order.product_image" :alt="order.product_name" />
              <div class="product-details">
                <h4>{{ order.product_name }}</h4>
                <p class="shares">购买{{ order.shares }}份</p>
                <p class="amount">¥{{ order.total_amount }}</p>
                <p class="progress" v-if="order.group_buy_progress">
                  拼购进度：{{ order.group_buy_progress }}
                  <span v-if="order.group_buy_status === 1" class="status-ongoing">进行中</span>
                  <span v-else-if="order.group_buy_status === 2" class="status-completed">已完成</span>
                  <span v-else class="status-pending">待开始</span>
                </p>
              </div>
            </div>
          </div>

          <div class="order-footer">
            <div class="order-time">{{ formatDate(order.created_at) }}</div>
            <div class="order-actions">
              <van-button 
                v-if="order.status === 'pending'" 
                size="small" 
                type="primary"
                @click.stop="payOrder(order)"
              >
                立即支付
              </van-button>
              <van-button 
                v-if="order.status === 'using'" 
                size="small"
                @click.stop="viewGroupBuy(order)"
              >
                查看拼购
              </van-button>
              <van-button 
                v-if="order.status === 'completed'" 
                size="small"
                @click.stop="viewCard(order)"
              >
                查看储值卡
              </van-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="filteredOrders.length === 0" class="empty-state">
        <van-empty description="暂无订单" />
        <van-button type="primary" @click="goToHome">去拼购</van-button>
      </div>
    </div>
  </LoginCheck>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { showToast } from 'vant'
import LoginCheck from '@/components/LoginCheck.vue'

// 订单数据类型定义
interface Order {
  id: number
  store_name: string
  store_logo: string
  product_name: string
  product_image: string
  shares: number
  total_amount: number
  status: string
  group_buy_progress: string
  group_buy_status: number
  created_at: string
}

const router = useRouter()
const authStore = useAuthStore()

// 当前激活的Tab
const activeTab = ref('all')

// 订单数据
const orders = ref<Order[]>([])
const loading = ref(false)

// 获取用户订单
const fetchOrders = async (status?: string) => {
  if (!authStore.userInfo?.phone) {
    showToast('请先登录')
    return
  }

  loading.value = true
  try {
    // 构建查询参数
    const params = new URLSearchParams({
      phone: authStore.userInfo.phone
    })
    
    // 如果有状态筛选，添加到查询参数
    if (status && status !== 'all') {
      params.append('status', status)
    }
    
    const response = await fetch(`/api/user/orders?${params.toString()}`)
    
    if (!response.ok) {
      throw new Error('获取订单失败')
    }
    
    const data = await response.json()
    // 按下单时间倒序排列
    orders.value = data.sort((a: Order, b: Order) => {
      return new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
    })
  } catch (error) {
    console.error('获取订单错误:', error)
    showToast('获取订单失败')
  } finally {
    loading.value = false
  }
}

// 监听Tab变化，重新获取订单数据
const handleTabChange = (name: string) => {
  activeTab.value = name
  fetchOrders(name)
}

// 根据Tab筛选订单（本地筛选，用于快速切换）
const filteredOrders = computed(() => {
  if (activeTab.value === 'all') {
    return orders.value
  }
  return orders.value.filter((order: Order) => order.status === activeTab.value)
})



// 格式化日期
const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 查看订单详情
const viewOrderDetail = (order: Order) => {
  console.log('查看订单详情', order)
  // TODO: 实现订单详情页面
}

// 支付订单
const payOrder = (order: Order) => {
  // 跳转到支付页面，传递订单信息
  router.push({
    name: 'Payment',
    params: { orderId: order.id },
    query: {
      store_name: order.store_name,
      store_logo: order.store_logo,
      product_name: order.product_name,
      product_image: order.product_image,
      shares: order.shares.toString(),
      total_amount: order.total_amount.toString()
    }
  })
}

// 查看拼购
const viewGroupBuy = (order: Order) => {
  console.log('查看拼购', order)
  // TODO: 跳转到拼购详情页
}

// 查看储值卡
const viewCard = (order: Order) => {
  console.log('查看储值卡', order)
  // TODO: 跳转到储值卡详情页
}

// 跳转到首页
const goToHome = () => {
  router.push('/')
}

// 页面加载时获取订单数据
onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.orders {
  background: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 20px; /* 额外底部边距，确保内容不被tabbar遮挡 */
}

.order-list {
  padding: 15px;
}

.order-item {
  background: white;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.store-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.store-info img {
  width: 28px;
  height: 28px;
  border-radius: 6px;
  object-fit: cover;
  border: 1px solid #eee;
}

.store-name {
  font-size: 14px;
  font-weight: bold;
}



.order-content {
  margin-bottom: 15px;
}

.product-info {
  display: flex;
  gap: 12px;
}

.product-info img {
  width: 70px;
  height: 70px;
  border-radius: 8px;
  object-fit: cover;
  border: 1px solid #eee;
}

.product-details h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  line-height: 1.4;
}

.product-details .shares {
  margin: 0 0 5px 0;
  font-size: 12px;
  color: #666;
}

.product-details .amount {
  margin: 0 0 5px 0;
  font-size: 18px;
  font-weight: bold;
  color: #ff6b6b;
}

.product-details .progress {
  margin: 0;
  font-size: 12px;
  color: #666;
}

.product-details .progress span {
  margin-left: 8px;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 10px;
  font-weight: bold;
}

.product-details .progress .status-ongoing {
  background: #e6f7ff;
  color: #1890ff;
}

.product-details .progress .status-completed {
  background: #f6ffed;
  color: #52c41a;
}

.product-details .progress .status-pending {
  background: #fff7e6;
  color: #fa8c16;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

.order-time {
  font-size: 12px;
  color: #666;
}

.order-actions {
  display: flex;
  gap: 8px;
}

.empty-state {
  padding: 60px 20px;
  text-align: center;
}
</style> 